package cn.com.sinosoft.ares.channel.service;

import cn.com.sinosoft.ares.common.util.XMLTools;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;
import java.util.Map;

/**
 * Description: 承保服务
 * Author: lishangmin
 * Created: 2018-09-13 10:46
 */
public abstract class AbstractTemplateService implements ITemplateService {

    private static String template = "";

    @Override
    public String fromXML(String message) {
        return this.fromXML(message,template);
    }

    @Override
    public String fromJSON(String message) {
        return this.fromJSON(message,template);
    }

    protected String fromXML(String message,String template){
        VelocityContext context = new VelocityContext();
        context.put("jsonObj", XMLTools.toJSONObject(message));
        StringWriter stringWriter = new StringWriter();
        Velocity.evaluate(context, stringWriter, "xmlVM", template);
        return stringWriter.toString();
    }

    protected String fromJSON(String message,String template){
        VelocityContext ctx = new VelocityContext();
        ctx.put("jsonObj", JSONObject.parseObject(message, Map.class));
        StringWriter stringWriter = new StringWriter();
        Velocity.evaluate(ctx, stringWriter, "jsonVM", template);
        return stringWriter.toString();
    }

    //验签
    protected void validSignature(String message,String sign ,String salt){
        if(StringUtils.isEmpty(sign)){
            throw new IllegalArgumentException();
        }
        //@TODO 实现MD5验签
    }

}
